<template>
  <div>
    <el-dialog v-model="$data.dlg_show" width="800px" :key="$data.version"
               :title="$data.row.apiDefine?.name + ' - API配置' ">

      <exec-api v-model="$data.row" @change="exec_callback"></exec-api>

      <el-button @click="config_ok" style="display: block;margin:20px auto;" type="primary">确 定</el-button>
    </el-dialog>

    <ref-api-define v-show="false" ref="apis" v-model="$data.willAddApis" multi @change="add_apis_change()">
    </ref-api-define>

    <input-table style="width:100%" ref="list"
                 :readOnly="$props.readOnly"
                 v-model="table" @add="api_add">

      <template #header>
        <div v-if="title" class="title">
          {{ title }}
        </div>
      </template>


      <el-table-column align="left" label="api定义" width="320px">
        <template v-slot="scope">
          <template v-if="scope.row.apiDefine.id">
            <el-tag>{{ scope.row.apiDefine.productLine.name }}</el-tag>
            <label style="margin-right: 4px;">.{{ scope.row.apiDefine.group }}</label>
          </template>
          <ref-api-define v-model="scope.row.apiDefine">
          </ref-api-define>
        </template>
      </el-table-column>

      <el-table-column align="left" label="url">
        <template v-slot="scope">
          <label class="link" @click="to_api(scope.row)">{{ scope.row.apiDefine.url }}</label>
        </template>
      </el-table-column>

      <el-table-column align="center" label="响应码" width="100px">
        <template v-slot="scope">
          <label v-if="!scope.row.status">{{ scope.row.status }}</label>
          <el-tag v-else-if="scope.row.status.Between(200,400)">{{ scope.row.status }}</el-tag>
          <el-tag v-else-if="!scope.row.status.Between(200,400)" type="warning" style="font-width: bold;">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="最后执行时间" width="140px">
        <template v-slot="scope">
          <label>{{ scope.row.lastExecuteAt?.slice(5) }}</label>
        </template>
      </el-table-column>

      <el-table-column type="expand">
        <template #default="scope">
          <kv label="参数">
            <div class="ps">
              <div class="item" v-for="(item) in scope.row.parameters" :key="item.key">
                <label>{{ item.key }}</label> <label>{{ item.value }}</label>
              </div>
            </div>
          </kv>
          <kv label="postBody">
            {{ scope.row.postBody }}
          </kv>
          <kv label="响应头">
            <div class="ps">
              <kp :label="key" v-for="(value,key) in scope.row.responseHeader" :key="key">
               <label>{{ value }}</label>
              </kp>
            </div>
          </kv>
          <kv label="响应">
            <preview-json :model-value=" JSON.parse( scope.row.responseBody || '{}') "></preview-json>
          </kv>
        </template>
      </el-table-column>

      <el-table-column align="center" label="配置" width="220px" class-name="thin">
        <template v-slot="scope">
          <el-button @click="show_config(scope.row)">配置</el-button>
          <el-button @click="run_click(scope.row, scope.$index)">执行</el-button>
          <el-button :style="{visibility: ( scope.$index < table.length -1)  ? 'visible': 'hidden'}"
                     @click="down_click(scope)">⤵
          </el-button>
          <el-button :style="{visibility: scope.$index ? 'visible': 'hidden'}" @click="up_click(scope)">⤴
          </el-button>
        </template>
      </el-table-column>
    </input-table>
  </div>
</template>

<script setup>
/**
 * Created by CodeGenerator at 2023-10-19 21:33:22
 */
import RefApiDefine from "../api-define/ref-api-define.vue"
import previewJson from "../../../component/preview-json.vue";
import execApi from "../../../component/exec-api.vue"



defineOptions({
  name: "ref-table-api-instance",
  inheritAttrs: true,
});

//定义 vue2的this,当前组件
const $self = getCurrentInstance();

//定义 $attrs
const $attrs = useAttrs();


//定义data
const $data = reactive({
  "willAddApis": [],
  "version": 0,
  "dlg_show": false,
  "row": {"postBody": ""},
  HttpMethod: jv.enum.HttpMethod.getData(),
  ApiParameterTypeEnum: jv.enum.ApiParameterTypeEnum.getData(),
  ApiParameterStringTypeEnum: jv.enum.ApiParameterStringTypeEnum.getData(),
  ApiJsonLocationEnum: jv.enum.ApiJsonLocationEnum.getData()
});


const $props = defineProps({
  title: {type: String},
  readOnly: {type: Boolean}
});


const $model = defineModel({type: Object});

const list = ref();

//定义事件
const $emit = defineEmits(["update:modelValue", "load"]);

const table = $computed({
  get() {
    return $model.value.apis;
  }, set(v) {
    var v = Object.assign({}, $model.value, {apis: v});
    $emit("update:modelValue", v);
  }
});

const exec_callback = ()=>{
  Object.assign( table.find(it=>it.id == $data.row.id) , $data.row);
}

const api_add = function (v, list) {
  list.splice(-1, 1)
  $data.willAddApis = [];
  this.$refs.apis.$refs.list.popClick();
};
const add_apis_change = function (v) {
  table.addAll(
      $data.willAddApis.map(it => {
        var v = {};
        v.apiDefine = it;
        v.parameters = [];
        v.postBody = "";
        return v;
      })
  );
};

const to_api = (row)=>{
  jv.$router.push("/dev/api-define/edit/" + row.apiDefine.id);
}
const run_click = async function (row, rowIndex) {
  if (!row.apiDefine.id) {
    return;
  }
  let res = await jv.$http.post("/dev/api-story/run-api?id=" + $model.value.id + "&index=" + rowIndex,
      {
        parameters: row.parameters,
        postBody: row.postBody,
        remark: row.remark
      })
//[axios拦截器中已处理了异常]。
  var status = res.data.data.apis[rowIndex].status;
  if (status.Between(200, 399)) {
    jv.info("运行成功, 状态码： " + status);
  } else {
    jv.error("运行失败, 状态码: " + status)
  }


  $emit("load", () => {
    list.value.mylist.getData().data.forEach(dbRow => {
      list.value.getElTable().toggleRowExpansion(dbRow, dbRow.id == row.id ? true : false);
    })
  });


};
const show_config = function (row) {
  if (!row.apiDefine.id) {
    return;
  }
  var ps = [], api = row.apiDefine;

  $data.version++;
  $data.row = row;
  $data.dlg_show = true;
};

const config_ok = function () {
  $data.dlg_show = false;
};
const procData = function (res, op) {
  let json = res.data.data;
  json.forEach(it => {
//如果是组合实体，设置 it.id=...
  });
};

const up_click = function (scope) {
  table.swap(scope.$index, scope.$index - 1);
};
const down_click = function (scope) {
  table.swap(scope.$index, scope.$index + 1);
};


const Json = function (value) {
  if (!value) {
    return {};
  }

  return JSON.parse(value);
}

</script>

<style scoped lang="scss">

::v-deep(.my-list) .kv {
  .k {
    flex: 1;
  }

  .v > :first-child {
    max-width: unset;
  }
}


.title {
  margin-top: 10px;

  &:after {
    content: "：";
    display: inline-block;
  }
}

.item {
  border: solid 3px gray;
  border-radius: 6px;
  display: inline-flex;
  flex-direction: row;
  flex-wrap: nowrap;
  margin-right: 10px;

  label {
    padding: 2px 4px;
  }

  label:first-child {
    background-color: gray;
    color: white;
  }
}

.item:not(:first-child) {
  margin-top: 6px;
}

pre {
  white-space: pre-wrap;
  word-wrap: break-word;
}

.ps ::v-deep(.kv) .k {
  flex: unset !important;
  min-width: 100px !important;
  color: red;
}


</style>